package com.heima.behavior.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.behavior.service.UserLikeBehaviorService;
import com.heima.behavior.thread.AppThreadLocalUtil;
import com.heima.common.cache.CacheService;
import com.heima.common.constants.BehaviorConstants;
import com.heima.model.behavoir.UpdateArticleMess;
import com.heima.model.behavoir.dtos.LikesBehaviorDto;
import com.heima.model.behavoir.dtos.ReadBehaviorDto;
import com.heima.model.behavoir.dtos.UnLikesBehaviorDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class UserLikeBehaviorServiceImpl implements UserLikeBehaviorService {

    @Autowired
    private CacheService cacheService;

    @Autowired
    private KafkaTemplate<String,String> kafkaTemplate;

    @Override
    public ResponseResult likesBehavior(LikesBehaviorDto dto) {

        // 1. 入参判空
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        // 2. 用户效验
        ApUser user = AppThreadLocalUtil.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
        }

        // 获取用户id
        Integer userId = user.getId();

        // 获取文章id
        Long articleId = dto.getArticleId();

        if (userId == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
        }

        // 3. 判断用户操作类型
        Short operation = dto.getOperation();
        if (0 == operation) {

            // 去重
            Object likeBehavior = cacheService.hGet(BehaviorConstants.LIKE_BEHAVIOR + articleId, userId.toString());
            if (likeBehavior != null) {
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST, "不可重复点赞");
            }

            // 写入点赞数据
            long currentTimeMillis = System.currentTimeMillis();
            cacheService.hPut(BehaviorConstants.LIKE_BEHAVIOR + articleId, userId.toString(), Long.toString(currentTimeMillis));

            // 点赞消息
            UpdateArticleMess updateArticleMess = new UpdateArticleMess();
            updateArticleMess.setAdd(1);
            updateArticleMess.setArticleId(articleId);
            updateArticleMess.setType(UpdateArticleMess.UpdateArticleType.LIKES);
            kafkaTemplate.send("itcast-topic-in",JSON.toJSONString(updateArticleMess));

        } else {

            // 删除点赞数据
            cacheService.hDelete(BehaviorConstants.LIKE_BEHAVIOR + articleId, userId.toString());

            // 取消点赞消息
            UpdateArticleMess updateArticleMess = new UpdateArticleMess();
            updateArticleMess.setAdd(-1);
            updateArticleMess.setArticleId(articleId);
            updateArticleMess.setType(UpdateArticleMess.UpdateArticleType.LIKES);
            kafkaTemplate.send("itcast-topic-in",JSON.toJSONString(updateArticleMess));
        }

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }


    @Override
    public ResponseResult readBehavior(ReadBehaviorDto dto) {

        // 1. 入参判空
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        // 2. 判断用户是否登录
        ApUser user = AppThreadLocalUtil.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
        }

        // 获取用户id
        Integer userId = user.getId();

        // 获取文章id
        Long articleId = dto.getArticleId();


        // 3.获取当前用户阅读数量
        String o = (String) cacheService.hGet(BehaviorConstants.READ_BEHAVIOR + articleId, userId.toString());

        if (o != null) {

            // 将查询的结果转换
            ReadBehaviorDto readBehaviorDto = JSON.parseObject(o, ReadBehaviorDto.class);
            Short totalCount = readBehaviorDto.getCount();
            Short currentCount = dto.getCount();

            // 将查询数据与传入的方法相加
            Short newCount = (short) (totalCount + currentCount);
            dto.setCount(newCount);
        }

        // 4. 更新当前用户的阅读数量
        cacheService.hPut(BehaviorConstants.READ_BEHAVIOR + articleId, userId.toString(), JSON.toJSONString(dto));

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }


    @Override
    public ResponseResult unLike(UnLikesBehaviorDto dto) {

        // 1. 入参判空
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        // 2. 判断当前用户是否登录
        ApUser user = AppThreadLocalUtil.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
        }

        Integer userId = user.getId();

        // 3. 判断用户操作类型
        Short type = dto.getType();
        Long articleId = dto.getArticleId();
        if (0 == type) {

            // 去重
            Object o = cacheService.hGet(BehaviorConstants.UN_LIKE_BEHAVIOR + articleId, userId.toString());
            if (o != null) {
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST, "不可重复操作");
            }

            // 写入数据
            cacheService.hPut(BehaviorConstants.UN_LIKE_BEHAVIOR + articleId, userId.toString(), JSON.toJSONString(dto));

        } else {

            // 取消不喜欢，删除数据
            cacheService.zRemove(BehaviorConstants.UN_LIKE_BEHAVIOR + articleId, userId.toString());

        }

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }


}
